<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const localStream = ref<MediaStream | null>(null)
const remoteStream = ref<MediaStream | null>(null)
const isCalling = ref(false)
const status = ref('准备连接')
const currentRoomId = ref('default-room') // TODO: 从路由或状态管理获取实际值
const currentUserId = ref(`user-${Math.random().toString(36).substr(2, 8)}`) // 生成随机用户ID

const pollingTimer = ref<number | null>(null)
const isCaller = ref(false) // 是否主叫
const peerConnection = ref<RTCPeerConnection | null>(null)
const signalingServer = 'https://enger.aigrow.space/ice/'

// 轮询对方offer（被叫方用）
async function pollOffers() {
  if (!currentRoomId.value || !currentUserId.value || !peerConnection.value) return
  try {
    const res = await fetch(`${signalingServer}/room/${currentRoomId.value}/offers`)
    const offers = await res.json()
    for (const [uid, offer] of Object.entries(offers)) {
      if (uid !== currentUserId.value && offer) {
        console.log('收到offer:', offer)
        // 收到对方offer，设置远端描述，生成answer
        await peerConnection.value!.setRemoteDescription(new RTCSessionDescription(offer as RTCSessionDescriptionInit))
        status.value = '收到offer，正在生成answer...'
        
        const answer = await peerConnection.value!.createAnswer()
        await peerConnection.value!.setLocalDescription(answer)
        
        // 发送answer
        const response = await fetch(`${signalingServer}/answer`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            answer: {
              sdp: answer.sdp,
              type: answer.type
            },
            user_id: currentUserId.value,
            room_id: currentRoomId.value
          })
        })
        
        const data = await response.json()
        console.log('Answer发送结果:', data)
        
        // 检查是否重复处理
        if (data.status === 'answer_already_processed' || data.status === 'connection_already_established') {
          console.log('Answer已处理过或连接已建立，跳过重复处理')
          return
        }
        
        status.value = '已应答，等待连接...'
        break
      }
    }
  } catch (error) {
    console.error('轮询offer失败:', error)
  }
}

// 轮询对方answer（主叫方用）
async function pollAnswers() {
  if (!currentRoomId.value || !currentUserId.value || !peerConnection.value) return
  try {
    const res = await fetch(`${signalingServer}/room/${currentRoomId.value}/answers`)
    const answers = await res.json()
    for (const [uid, answer] of Object.entries(answers)) {
      if (uid !== currentUserId.value && answer) {
        console.log('收到answer:', answer)
        await peerConnection.value!.setRemoteDescription(new RTCSessionDescription(answer as RTCSessionDescriptionInit))
        status.value = '对方已应答，等待连接...'
        break
      }
    }
  } catch (error) {
    console.error('轮询answer失败:', error)
  }
}

// 轮询ICE
async function pollCandidates() {
  if (!currentRoomId.value || !currentUserId.value || !peerConnection.value) return
  try {
    const res = await fetch(`${signalingServer}/room/${currentRoomId.value}/candidates`)
    const candidates = await res.json()
    for (const [uid, candList] of Object.entries(candidates)) {
      if (uid !== currentUserId.value && Array.isArray(candList)) {
        for (const cand of candList as any[]) {
          try {
            console.log('添加ICE候选:', cand)
            await peerConnection.value!.addIceCandidate(new RTCIceCandidate(cand))
          } catch (e) {
            // 可能重复添加，忽略
            console.log('ICE候选添加失败（可能重复）:', e)
          }
        }
      }
    }
  } catch (error) {
    console.error('轮询ICE失败:', error)
  }
}

// 检查连接状态
async function checkConnectionStatus() {
  if (!currentUserId.value) return false
  try {
    const res = await fetch(`${signalingServer}/connection/status/${currentUserId.value}`)
    const status = await res.json()
    return status.connection_established || false
  } catch (error) {
    console.error('检查连接状态失败:', error)
    return false
  }
}

// 标记连接已建立
async function markConnectionEstablished() {
  if (!currentUserId.value || !currentRoomId.value) return
  try {
    await fetch(`${signalingServer}/connection/established`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        user_id: currentUserId.value,
        room_id: currentRoomId.value
      })
    })
    console.log('已标记连接建立')
  } catch (error) {
    console.error('标记连接建立失败:', error)
  }
}

// 统一轮询调度
function startPollingAll() {
  stopPollingAll()
  pollingTimer.value = setInterval(async () => {
    // 检查连接是否已建立
    const isConnected = await checkConnectionStatus()
    if (isConnected) {
      console.log('连接已建立，停止轮询')
      stopPollingAll()
      return
    }
    
    if (isCaller.value) {
      await pollAnswers()
    } else {
      await pollOffers()
    }
    await pollCandidates()
  }, 1500)
}

function stopPollingAll() {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

// 获取本地音频和视频流
async function getLocalStream() {
  try {
    status.value = '正在请求麦克风和摄像头权限...'
    console.log('开始获取媒体流...')
    
    // 检测浏览器类型
    const isFirefox = navigator.userAgent.toLowerCase().includes('firefox')
    const isChrome = navigator.userAgent.toLowerCase().includes('chrome')
    console.log(`检测到浏览器: ${isFirefox ? 'Firefox' : isChrome ? 'Chrome' : '其他'}`)
    
    // 根据浏览器调整媒体约束
    const constraints = {
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        autoGainControl: true
      },
      video: {
        width: { ideal: 640, min: 320, max: 1280 },
        height: { ideal: 480, min: 240, max: 720 },
        facingMode: 'user',
        frameRate: { ideal: 30, min: 15, max: 60 }
      }
    }
    
    // Firefox特定优化
    if (isFirefox) {
      constraints.video = {
        width: { ideal: 640, min: 320, max: 1280 },
        height: { ideal: 480, min: 240, max: 720 },
        facingMode: 'user',
        frameRate: { ideal: 30, min: 15, max: 60 }
      }
    }
    
    localStream.value = await navigator.mediaDevices.getUserMedia(constraints)
    
    console.log('成功获取媒体流:', localStream.value)
    console.log('媒体轨道数量:', localStream.value.getTracks().length)
    console.log('音频轨道:', localStream.value.getAudioTracks())
    console.log('视频轨道:', localStream.value.getVideoTracks())
    
    status.value = '已获取麦克风和摄像头权限'
    
    // 应用Firefox特定的视频修复
    fixFirefoxVideoDisplay()
    
  } catch (error) {
    console.error('获取媒体设备失败:', error)
    
    // 尝试只获取音频
    try {
      status.value = '摄像头权限被拒绝，尝试只获取音频...'
      console.log('尝试只获取音频...')
      
      localStream.value = await navigator.mediaDevices.getUserMedia({ 
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true
        },
        video: false
      })
      
      console.log('成功获取音频流:', localStream.value)
      console.log('音频轨道数量:', localStream.value.getAudioTracks().length)
      
      status.value = '已获取麦克风权限（仅音频模式）'
      
    } catch (audioError) {
      console.error('获取音频设备也失败:', audioError)
      status.value = '无法获取媒体设备权限，请检查浏览器设置'
      
      // 即使没有媒体流，也允许用户继续（可能是测试环境）
      if (error instanceof Error) {
        if (error.name === 'NotAllowedError') {
          status.value = '媒体权限被拒绝，但可以继续测试信令流程'
        } else if (error.name === 'NotFoundError') {
          status.value = '未找到媒体设备，但可以继续测试信令流程'
        } else {
          status.value = '媒体设备错误，但可以继续测试信令流程'
        }
      } else {
        status.value = '媒体设备错误，但可以继续测试信令流程'
      }
    }
  }
}

// 初始化PeerConnection
function initPeerConnection() {
  const pc = new RTCPeerConnection({
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' }
    ]
  })
  
  // 添加本地流（如果有的话）
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => {
      pc.addTrack(track, localStream.value!)
    })
    console.log('已添加本地媒体轨道到PeerConnection')
  } else {
    console.log('没有本地媒体流，将创建空的PeerConnection用于信令测试')
  }
  
  // 监听ICE候选
  pc.onicecandidate = (event) => {
    if (event.candidate) {
      console.log('发送ICE候选:', event.candidate)
      // 发送ICE候选到信令服务器
      if (!currentRoomId.value || !currentUserId.value) {
        console.error('无法发送ICE候选: 缺少房间ID或用户ID')
        return
      }
      
      fetch(`${signalingServer}/ice`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          candidate: {
            candidate: event.candidate.candidate,
            sdpMid: event.candidate.sdpMid,
            sdpMLineIndex: event.candidate.sdpMLineIndex
          },
          user_id: currentUserId.value,
          room_id: currentRoomId.value
        })
      }).then(response => response.json())
        .then(data => {
          // 检查是否重复处理
          if (data.status === 'ice_candidate_duplicate') {
            console.log('ICE候选已存在，跳过重复发送')
          }
        })
        .catch(err => {
        console.error('发送ICE候选失败:', err)
      })
    } else {
      console.log('ICE候选收集完成')
    }
  }
  
  // 监听ICE连接状态
  pc.oniceconnectionstatechange = () => {
    console.log('ICE连接状态:', pc.iceConnectionState)
    if (pc.iceConnectionState === 'connected') {
      status.value = 'ICE连接已建立'
    } else if (pc.iceConnectionState === 'failed') {
      status.value = 'ICE连接失败'
    } else if (pc.iceConnectionState === 'checking') {
      status.value = '正在检查ICE连接...'
    }
  }
  
  // 监听ICE收集状态
  pc.onicegatheringstatechange = () => {
    console.log('ICE收集状态:', pc.iceGatheringState)
  }
  
  // 监听信令状态
  pc.onsignalingstatechange = () => {
    console.log('信令状态:', pc.signalingState)
  }
  
  // 监听远程流
  pc.ontrack = (event) => {
    console.log('收到远程流:', event.streams)
    remoteStream.value = event.streams[0]
    status.value = '已接收远程音视频流'
  }
  
  // 监听连接状态变化
  pc.onconnectionstatechange = () => {
    console.log('连接状态:', pc.connectionState)
    if (pc.connectionState === 'connected') {
      status.value = 'WebRTC连接已建立，音视频通话开始！'
      // 标记连接已建立，停止轮询
      markConnectionEstablished()
      stopPollingAll()
    } else if (pc.connectionState === 'failed') {
      status.value = 'WebRTC连接失败'
    } else if (pc.connectionState === 'connecting') {
      status.value = '正在建立WebRTC连接...'
    } else if (pc.connectionState === 'disconnected') {
      status.value = 'WebRTC连接已断开'
    }
  }
  
  peerConnection.value = pc
}

// 初始化通话设置
async function initCall() {
  if (!currentRoomId.value.trim() || !currentUserId.value.trim()) {
    alert('请输入有效的用户ID和房间ID')
    return
  }
  
  isCalling.value = true
  status.value = `已设置为${isCaller.value ? '主叫方' : '被叫方'}，准备开始通话`
  
  // 尝试获取媒体流
  if (!localStream.value) {
    status.value = '正在获取媒体权限...'
    await getLocalStream()
  }
}

// 开始通话
async function startCall() {
  // 检查连接是否已建立
  const isConnected = await checkConnectionStatus()
  if (isConnected) {
    status.value = '连接已建立，无需重复开始通话'
    return
  }
  
  isCalling.value = true
  status.value = '正在建立连接...'
  
  try {
    // 确保获取本地媒体流
    if (!localStream.value) {
      status.value = '正在获取媒体权限...'
      await getLocalStream()
    }
    
    initPeerConnection()
    
    if (isCaller.value) {
      // 主叫方发offer
      status.value = '正在创建offer...'
      const offer = await peerConnection.value!.createOffer()
      await peerConnection.value!.setLocalDescription(offer)
      
      // 发送offer到信令服务器
      if (!currentRoomId.value || !currentUserId.value) {
        throw new Error('无法发送offer: 缺少房间ID或用户ID')
      }
      
      const response = await fetch(`${signalingServer}/offer`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          offer: {
            sdp: offer.sdp,
            type: offer.type
          },
          user_id: currentUserId.value,
          room_id: currentRoomId.value
        })
      })
      
      const data = await response.json()
      console.log('Server response:', data)
      
      // 检查是否重复处理
      if (data.status === 'offer_already_processed' || data.status === 'connection_already_established') {
        console.log('Offer已处理过或连接已建立，跳过重复处理')
        status.value = data.message || '连接已建立或处理中'
        return
      }
      
      if (data.status === 'waiting_for_peer') {
        status.value = data.message || '等待其他用户加入...'
      } else if (data.status === 'offer_sent') {
        status.value = data.message || 'Offer已发送，等待对方应答...'
      }
    } else {
      // 被叫方不主动发offer，等待轮询
      status.value = '等待对方发起通话...'
    }
    
    // 开始轮询
    startPollingAll()
    
  } catch (error) {
    console.error('连接失败:', error)
    status.value = '连接失败'
    endCall()
  }
}

// 结束通话
function endCall() {
  // 停止轮询
  stopPollingAll()
  
  // 关闭PeerConnection
  if (peerConnection.value) {
    peerConnection.value.close()
    peerConnection.value = null
  }
  
  // 停止音频流
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop())
    localStream.value = null
  }
  if (remoteStream.value) {
    remoteStream.value.getTracks().forEach(track => track.stop())
    remoteStream.value = null
  }
  
  isCalling.value = false
  status.value = '通话已结束'
}

// 离开房间
async function leaveRoom() {
  if (currentUserId.value && currentRoomId.value) {
    try {
      await fetch(`${signalingServer}/room/leave`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: currentUserId.value,
          room_id: currentRoomId.value
        })
      })
    } catch (error) {
      console.error('离开房间失败:', error)
    }
  }
}

// 刷新媒体流
function refreshMediaStream() {
  getLocalStream()
}

// 本地视频事件处理
function onLocalVideoLoaded() {
  console.log('本地视频元数据已加载')
  status.value = '本地视频已准备就绪'
  
  // 确保视频播放
  if (localStream.value) {
    // 使用ID查找视频元素
    let videoElement = document.getElementById('localVideoElement') as HTMLVideoElement
    
    // 备用方案
    if (!videoElement) {
      videoElement = document.querySelector('video[ref="localVideo"]') as HTMLVideoElement
    }
    if (!videoElement) {
      videoElement = document.querySelector('.video-element') as HTMLVideoElement
    }
    
    if (videoElement) {
      console.log('找到本地视频元素，确保播放')
      ensureVideoPlayback(videoElement, localStream.value)
    } else {
      console.log('未找到本地视频元素')
    }
  }
}

function onLocalVideoCanPlay() {
  console.log('本地视频可以播放')
  status.value = '本地视频正在播放'
}

function onLocalVideoError(event: Event) {
  console.error('本地视频播放错误:', event)
  status.value = '本地视频播放出错'
}

// 远程视频事件处理
function onRemoteVideoLoaded() {
  console.log('远程视频元数据已加载')
  status.value = '远程视频已准备就绪'
  
  // 确保视频播放
  if (remoteStream.value) {
    const videoElement = document.querySelector('.video-element[ref="remoteVideo"]') as HTMLVideoElement
    if (videoElement) {
      ensureVideoPlayback(videoElement, remoteStream.value)
    }
  }
}

function onRemoteVideoCanPlay() {
  console.log('远程视频可以播放')
  status.value = '远程视频正在播放'
}

function onRemoteVideoError(event: Event) {
  console.error('远程视频播放错误:', event)
  status.value = '远程视频播放出错'
}

// Firefox特定的视频修复
function fixFirefoxVideoDisplay() {
  // 检测是否为Firefox
  const isFirefox = navigator.userAgent.toLowerCase().includes('firefox')
  if (isFirefox) {
    console.log('检测到Firefox，应用视频显示修复')
    
    // 延迟执行，确保DOM已更新
    setTimeout(() => {
      // 使用ID查找视频元素
      let localVideo = document.getElementById('localVideoElement') as HTMLVideoElement
      let remoteVideo = document.getElementById('remoteVideoElement') as HTMLVideoElement
      
      // 备用方案：通过其他方式查找
      if (!localVideo) {
        localVideo = document.querySelector('video[ref="localVideo"]') as HTMLVideoElement
      }
      if (!localVideo) {
        localVideo = document.querySelector('.video-element') as HTMLVideoElement
      }
      
      if (!remoteVideo) {
        remoteVideo = document.querySelector('video[ref="remoteVideo"]') as HTMLVideoElement
      }
      if (!remoteVideo) {
        const videos = document.querySelectorAll('.video-element')
        if (videos.length > 1) {
          remoteVideo = videos[1] as HTMLVideoElement
        }
      }
      
      if (localVideo && localStream.value) {
        console.log('重新设置本地视频流')
        try {
          // 先清除现有流
          localVideo.srcObject = null
          localVideo.load() // 强制重新加载
          
          setTimeout(() => {
            // 重新设置流
            localVideo.srcObject = localStream.value
            console.log('已设置本地视频流到元素:', localVideo)
            
            // 尝试播放
            const playPromise = localVideo.play()
            if (playPromise !== undefined) {
              playPromise
                .then(() => {
                  console.log('Firefox本地视频播放成功')
                  status.value = 'Firefox本地视频已开始播放'
                })
                .catch(e => {
                  console.log('Firefox本地视频播放失败:', e)
                  status.value = 'Firefox本地视频播放失败，可能需要用户交互'
                })
            }
          }, 200)
        } catch (e) {
          console.error('设置本地视频流失败:', e)
        }
      }
      
      if (remoteVideo && remoteStream.value) {
        console.log('重新设置远程视频流')
        try {
          remoteVideo.srcObject = null
          remoteVideo.load()
          
          setTimeout(() => {
            remoteVideo.srcObject = remoteStream.value
            console.log('已设置远程视频流到元素:', remoteVideo)
            
            const playPromise = remoteVideo.play()
            if (playPromise !== undefined) {
              playPromise
                .then(() => {
                  console.log('Firefox远程视频播放成功')
                })
                .catch(e => {
                  console.log('Firefox远程视频播放失败:', e)
                })
            }
          }, 200)
        } catch (e) {
          console.error('设置远程视频流失败:', e)
        }
      }
    }, 1000) // 增加延迟时间
  }
}

// 通用的视频播放函数
function ensureVideoPlayback(videoElement: HTMLVideoElement, stream: MediaStream) {
  if (!videoElement || !stream) return
  
  try {
    // 设置视频源
    videoElement.srcObject = stream
    
    // 尝试播放视频
    const playPromise = videoElement.play()
    if (playPromise !== undefined) {
      playPromise
        .then(() => {
          console.log('视频播放成功')
        })
        .catch(error => {
          console.log('视频播放失败，可能需要用户交互:', error)
          // 在Firefox中，可能需要用户交互才能播放
          if (navigator.userAgent.toLowerCase().includes('firefox')) {
            console.log('Firefox中需要用户交互才能播放视频')
          }
        })
    }
  } catch (error) {
    console.error('设置视频流失败:', error)
  }
}

// 强制刷新Firefox视频
function forceRefreshFirefoxVideo() {
  console.log('=== Firefox视频修复调试信息 ===')
  console.log('浏览器信息:', navigator.userAgent)
  console.log('本地流状态:', localStream.value)
  console.log('远程流状态:', remoteStream.value)
  
  // 查找所有视频元素
  const allVideos = document.querySelectorAll('video')
  console.log('页面中的视频元素数量:', allVideos.length)
  
  allVideos.forEach((video, index) => {
    console.log(`视频元素 ${index}:`, {
      id: video.id,
      className: video.className,
      srcObject: video.srcObject,
      readyState: video.readyState,
      paused: video.paused,
      currentTime: video.currentTime
    })
  })
  
  // 调用Firefox特定的视频修复函数
  fixFirefoxVideoDisplay()
}

onMounted(() => {
  getLocalStream()
})

onUnmounted(() => {
  endCall()
  leaveRoom()
})
</script>

<template>
  <div class="mdc-container">
    <div class="mdc-card main-card">
      <div class="card-header">
        <h1 class="card-title">
          <span class="material-icon">videocam</span>
          音视频通话
        </h1>
        <p class="card-subtitle">WebRTC 实时音视频通信</p>
      </div>
      
      <div class="card-content">
        <!-- Setup Section -->
        <div v-if="!isCalling" class="setup-section">
          <div class="mdc-card setup-card">
            <div class="card-content">
              <h2 class="section-title">
                <span class="material-icon">settings</span>
                连接设置
              </h2>
              
      <div class="form-group">
                <label class="mdc-label">
                  <span class="material-icon">person</span>
                  用户ID
                </label>
                <div class="mdc-text-field">
        <input 
                    class="mdc-input"
          v-model="currentUserId" 
          placeholder="请输入用户ID"
        />
      </div>
              </div>
              
      <div class="form-group">
                <label class="mdc-label">
                  <span class="material-icon">meeting_room</span>
                  房间ID
                </label>
                <div class="mdc-text-field">
        <input 
                    class="mdc-input"
          v-model="currentRoomId" 
          placeholder="请输入房间ID"
        />
      </div>
              </div>
              
              <div class="form-group">
                <label for="roleSelect">角色设置:</label>
                <select 
                  id="roleSelect" 
                  v-model="isCaller" 
                  class="mdc-select"
                >
                  <option :value="true">主叫方 (主动发起通话)</option>
                  <option :value="false">被叫方 (等待对方发起)</option>
                </select>
                <p class="role-hint">
                  {{ isCaller ? '主叫方：主动发起通话，发送offer' : '被叫方：等待对方发起，接收offer后应答' }}
                </p>
              </div>
              
              <div class="action-buttons">
      <button 
        @click="initCall" 
                  :disabled="!currentUserId.trim() || !currentRoomId.trim()"
                  class="mdc-button mdc-button--raised primary"
      >
                  <span class="material-icon">check_circle</span>
        验证输入
      </button>
              </div>
              
              <div class="info-box">
                <p class="info-text">
                  <span class="material-icon">info</span>
                  请输入用户ID和房间ID，选择角色，然后点击"验证输入"确认。<br>
                  确认后将可以点击"开始通话"建立实际连接。<br>
                  <strong>注意：</strong>首次使用需要允许浏览器访问麦克风和摄像头权限。<br>
                  <strong>测试模式：</strong>即使没有媒体权限，也可以测试WebRTC信令流程。
                </p>
              </div>
            </div>
          </div>
    </div>
    
        <!-- Call Section -->
    <div v-else>
          <!-- Status Section -->
          <div class="mdc-card status-card">
            <div class="card-content">
              <h2 class="status-title">
                <span class="material-icon">info</span>
                连接状态
              </h2>
              
              <div class="status-grid">
                <div class="status-item">
                  <span class="status-label">状态:</span>
                  <span class="status-value">{{ status }}</span>
                </div>
                <div class="status-item">
                  <span class="status-label">角色:</span>
                  <span class="status-value">{{ isCaller ? '主叫方' : '被叫方' }}</span>
                </div>
                <div class="status-item">
                  <span class="status-label">用户ID:</span>
                  <span class="status-value">{{ currentUserId }}</span>
                </div>
                <div class="status-item">
                  <span class="status-label">房间ID:</span>
                  <span class="status-value">{{ currentRoomId }}</span>
                </div>
                <div v-if="peerConnection" class="status-item">
                  <span class="status-label">连接状态:</span>
                  <span class="status-value">{{ peerConnection.connectionState }}</span>
                </div>
                <div v-if="peerConnection" class="status-item">
                  <span class="status-label">ICE状态:</span>
                  <span class="status-value">{{ peerConnection.iceConnectionState }}</span>
                </div>
                <div v-if="peerConnection" class="status-item">
                  <span class="status-label">信令状态:</span>
                  <span class="status-value">{{ peerConnection.signalingState }}</span>
                </div>
                <div v-if="localStream" class="status-item">
                  <span class="status-label">本地流:</span>
                  <span class="status-value">{{ localStream.getTracks().length }} 个轨道 (音频: {{ localStream.getAudioTracks().length }}, 视频: {{ localStream.getVideoTracks().length }})</span>
                </div>
                <div v-else class="status-item">
                  <span class="status-label">本地流:</span>
                  <span class="status-value">未获取媒体流（仅信令测试模式）</span>
                </div>
                <div v-if="remoteStream" class="status-item">
                  <span class="status-label">远程流:</span>
                  <span class="status-value">{{ remoteStream.getTracks().length }} 个轨道 (音频: {{ remoteStream.getAudioTracks().length }}, 视频: {{ remoteStream.getVideoTracks().length }})</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Video Section -->
          <div class="video-section">
            <div class="mdc-card video-card">
              <div class="card-content">
                <h2 class="section-title">
                  <span class="material-icon">videocam</span>
                  视频流
                </h2>
                
                <div class="video-grid">
                  <div class="video-item">
                    <div class="video-header">
                      <span class="material-icon">person</span>
                      本地视频
                    </div>
                    <div class="video-container">
                      <video 
                        v-if="localStream" 
                        :srcObject="localStream" 
                        autoplay 
                        muted
                        playsinline
                        webkit-playsinline
                        x5-playsinline
                        x5-video-player-type="h5"
                        x5-video-player-fullscreen="true"
                        class="video-element"
                        style="transform: scaleX(-1);"
                        @loadedmetadata="onLocalVideoLoaded"
                        @canplay="onLocalVideoCanPlay"
                        @error="onLocalVideoError"
                        ref="localVideo"
                        id="localVideoElement"
                      ></video>
                      <div v-else class="video-placeholder">
                        <span class="material-icon">videocam_off</span>
                        <p>未获取摄像头权限</p>
                      </div>
                    </div>
                  </div>
                  
                  <div class="video-item">
                    <div class="video-header">
                      <span class="material-icon">person_add</span>
                      远程视频
                    </div>
                    <div class="video-container">
                      <video 
                        v-if="remoteStream" 
                        :srcObject="remoteStream" 
                        autoplay 
                        playsinline
                        webkit-playsinline
                        x5-playsinline
                        x5-video-player-type="h5"
                        x5-video-player-fullscreen="true"
                        class="video-element"
                        @loadedmetadata="onRemoteVideoLoaded"
                        @canplay="onRemoteVideoCanPlay"
                        @error="onRemoteVideoError"
                        ref="remoteVideo"
                        id="remoteVideoElement"
                      ></video>
                      <div v-else class="video-placeholder">
                        <span class="material-icon">hourglass_empty</span>
                        <p>等待对方视频流...</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Audio Section -->
          <div class="audio-section">
            <div class="mdc-card audio-card">
              <div class="card-content">
                <h2 class="section-title">
                  <span class="material-icon">mic</span>
                  音频流
                </h2>
                
                <div class="audio-grid">
                  <div class="audio-item">
                    <div class="audio-header">
                      <span class="material-icon">mic</span>
                      本地音频 (麦克风)
                    </div>
                    <audio 
                      v-if="localStream" 
                      :srcObject="localStream" 
                      autoplay 
                      muted
                      controls
                      class="audio-element"
                    ></audio>
                    <div v-else class="audio-placeholder">
                      <span class="material-icon">mic_off</span>
                      <p>未获取麦克风权限</p>
                    </div>
                  </div>
                  
                  <div class="audio-item">
                    <div class="audio-header">
                      <span class="material-icon">volume_up</span>
                      远程音频 (对方)
                    </div>
                    <audio 
                      v-if="remoteStream" 
                      :srcObject="remoteStream" 
                      autoplay 
                      controls
                      class="audio-element"
                    ></audio>
                    <div v-else class="audio-placeholder">
                      <span class="material-icon">hourglass_empty</span>
                      <p>等待对方音频流...</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Control Section -->
          <div class="control-section">
            <div class="mdc-card control-card">
              <div class="card-content">
                <div class="control-buttons">
                  <button @click="startCall" :disabled="!currentUserId.trim() || !currentRoomId.trim()" class="mdc-button mdc-button--raised success">
                    <span class="material-icon">call</span>
                    开始音视频通话
                  </button>
                  <button @click="refreshMediaStream" class="mdc-button mdc-button--raised primary">
                    <span class="material-icon">refresh</span>
                    刷新媒体流
                  </button>
                  <button @click="forceRefreshFirefoxVideo" class="mdc-button mdc-button--raised warning">
                    <span class="material-icon">bug_report</span>
                    Firefox视频修复
                  </button>
                  <button @click="endCall" class="mdc-button mdc-button--raised danger">
                    <span class="material-icon">call_end</span>
                    结束通话
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Material Icons Font Import - 必须在顶部 */
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');

/* Material Design Light Theme */
:root {
  --mdc-primary: #6200ee;
  --mdc-primary-variant: #3700b3;
  --mdc-secondary: #03dac6;
  --mdc-background: #ffffff;
  --mdc-surface: #ffffff;
  --mdc-error: #b00020;
  --mdc-on-primary: #ffffff;
  --mdc-on-secondary: #000000;
  --mdc-on-background: #000000;
  --mdc-on-surface: #000000;
  --mdc-on-error: #ffffff;
  --mdc-elevation-1: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  --mdc-elevation-2: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
  --mdc-elevation-4: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
  --mdc-border-radius: 8px;
  --mdc-spacing: 16px;
}

/* Container */
.mdc-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: var(--mdc-spacing);
  font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

/* Cards */
.mdc-card {
  background: var(--mdc-surface);
  border-radius: var(--mdc-border-radius);
  box-shadow: var(--mdc-elevation-1);
  transition: box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.mdc-card:hover {
  box-shadow: var(--mdc-elevation-2);
}

.main-card {
  max-width: 1200px;
  margin: 0 auto;
  box-shadow: var(--mdc-elevation-4);
}

.card-header {
  background: linear-gradient(135deg, var(--mdc-primary), var(--mdc-primary-variant));
  color: var(--mdc-on-primary);
  padding: calc(var(--mdc-spacing) * 2);
  text-align: center;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 2rem;
  font-weight: 300;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.card-subtitle {
  margin: 0;
  font-size: 1rem;
  opacity: 0.87;
  font-weight: 300;
}

.card-content {
  padding: calc(var(--mdc-spacing) * 1.5);
}

/* Material Icons - Firefox兼容性修复 */
.material-icon {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  vertical-align: middle;
  /* Firefox特定修复 */
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

/* Setup Section */
.setup-section {
  margin-top: var(--mdc-spacing);
}

.setup-card {
  margin-bottom: var(--mdc-spacing);
}

.form-group {
  margin-bottom: calc(var(--mdc-spacing) * 1.5);
}

.mdc-label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--mdc-on-surface);
  font-size: 0.875rem;
}

.mdc-text-field {
  position: relative;
}

.mdc-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s, box-shadow 0.3s;
  background: #fafafa;
  /* Firefox特定修复 */
  -moz-appearance: none;
  appearance: none;
}

.mdc-input:focus {
  outline: none;
  border-color: var(--mdc-primary);
  box-shadow: 0 0 0 2px rgba(98, 0, 238, 0.2);
  background: white;
}

.mdc-input::placeholder {
  color: #757575;
}

/* Material Design Select Styles */
.mdc-select {
  width: 100%;
  max-width: 300px;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: #fff;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  color: #212121;
  cursor: pointer;
  transition: border-color 0.3s, box-shadow 0.3s;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 12px center;
  background-size: 16px;
  padding-right: 40px;
  /* Firefox特定修复 */
  -moz-appearance: none;
}

.mdc-select:focus {
  outline: none;
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.mdc-select:hover {
  border-color: #1976d2;
}

.mdc-select option {
  padding: 8px;
  background: #fff;
  color: #212121;
}

.role-hint {
  font-size: 0.875rem;
  color: #666;
  margin-top: 8px;
  line-height: 1.4;
}

/* Buttons - Firefox兼容性修复 */
.mdc-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 36px;
  /* Firefox特定修复 */
  -moz-appearance: none;
  appearance: none;
  /* 确保按钮可以点击 */
  position: relative;
  z-index: 1;
  /* 修复Firefox中的点击区域 */
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.mdc-button--raised {
  box-shadow: var(--mdc-elevation-1);
}

.mdc-button--raised:hover {
  box-shadow: var(--mdc-elevation-2);
}

.mdc-button.primary {
  background: var(--mdc-primary);
  color: var(--mdc-on-primary);
}

.mdc-button.primary:hover {
  background: var(--mdc-primary-variant);
}

.mdc-button.success {
  background: #4caf50;
  color: white;
}

.mdc-button.success:hover {
  background: #388e3c;
}

.mdc-button.danger {
  background: var(--mdc-error);
  color: var(--mdc-on-error);
}

.mdc-button.danger:hover {
  background: #8e0000;
}

.mdc-button:disabled {
  background: #e0e0e0;
  color: #757575;
  cursor: not-allowed;
  box-shadow: none;
  /* Firefox禁用状态修复 */
  opacity: 0.6;
}

.action-buttons {
  margin: calc(var(--mdc-spacing) * 1.5) 0;
  text-align: center;
}

/* Info Box */
.info-box {
  background: #e3f2fd;
  border-left: 4px solid #2196f3;
  padding: 16px;
  border-radius: 4px;
  margin-top: var(--mdc-spacing);
}

.info-text {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.5;
  color: #1565c0;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

/* Call Section */
.call-section {
  margin-top: var(--mdc-spacing);
}

.status-card {
  margin-bottom: var(--mdc-spacing);
}

.status-title {
  margin: 0 0 16px 0;
  font-size: 1.25rem;
  font-weight: 500;
  color: var(--mdc-on-surface);
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-label {
  font-weight: 500;
  color: #666;
  font-size: 0.875rem;
}

.status-value {
  font-weight: 400;
  color: var(--mdc-on-surface);
  font-size: 0.875rem;
  text-align: right;
  max-width: 200px;
  word-break: break-word;
}

/* Video Section */
.video-section {
  margin-bottom: var(--mdc-spacing);
}

.video-card {
  margin-bottom: var(--mdc-spacing);
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 1.25rem;
  font-weight: 500;
  color: var(--mdc-on-surface);
  display: flex;
  align-items: center;
  gap: 8px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.video-item {
  display: flex;
  flex-direction: column;
}

.video-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: var(--mdc-on-surface);
  font-size: 0.875rem;
}

.video-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: #000;
  aspect-ratio: 16/9;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  /* 确保视频在所有浏览器中正确显示 */
  background: #000;
  /* Chrome和Firefox兼容性 */
  -webkit-transform: scaleX(-1);
  -moz-transform: scaleX(-1);
  transform: scaleX(-1);
  /* 确保视频元素可以正确播放 */
  display: block;
}

.video-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #757575;
  background: #f5f5f5;
}

.video-placeholder .material-icon {
  font-size: 48px;
  margin-bottom: 8px;
  opacity: 0.5;
}

.video-placeholder p {
  margin: 0;
  font-size: 0.875rem;
  text-align: center;
}

/* Audio Section */
.audio-section {
  margin-bottom: var(--mdc-spacing);
}

.audio-card {
  margin-bottom: var(--mdc-spacing);
}

.audio-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.audio-item {
  display: flex;
  flex-direction: column;
}

.audio-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: var(--mdc-on-surface);
  font-size: 0.875rem;
}

.audio-element {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.audio-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #757575;
  background: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.audio-placeholder .material-icon {
  font-size: 32px;
  margin-bottom: 8px;
  opacity: 0.5;
}

.audio-placeholder p {
  margin: 0;
  font-size: 0.875rem;
  text-align: center;
}

/* Control Section */
.control-section {
  margin-top: var(--mdc-spacing);
}

.control-card {
  margin-bottom: var(--mdc-spacing);
}

.control-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  flex-wrap: wrap;
}

/* 按钮样式扩展 */
.mdc-button--raised.warning {
  background: #ff9800;
  color: white;
}

.mdc-button--raised.warning:hover {
  background: #f57c00;
  box-shadow: 0 3px 6px rgba(0,0,0,0.16);
}

/* Responsive Design */
@media (max-width: 768px) {
  .mdc-container {
    padding: 8px;
  }
  
  .card-content {
    padding: var(--mdc-spacing);
  }
  
  .status-grid {
    grid-template-columns: 1fr;
  }
  
  .video-grid {
    grid-template-columns: 1fr;
  }
  
  .audio-grid {
    grid-template-columns: 1fr;
  }
  
  .control-buttons {
    flex-direction: column;
  }
  
  .card-title {
    font-size: 1.5rem;
  }
}

/* Firefox特定修复 */
@-moz-document url-prefix() {
  .mdc-button {
    /* 确保Firefox中的按钮可以正确点击 */
    pointer-events: auto;
    /* 修复Firefox中的按钮样式 */
    background-clip: padding-box;
  }
  
  .mdc-input,
  .mdc-select {
    /* 修复Firefox中的输入框样式 */
    background-clip: padding-box;
  }
  
  .video-element {
    /* 修复Firefox中的视频显示问题 */
    object-fit: cover;
    width: 100%;
    height: 100%;
    /* 确保视频在Firefox中正确渲染 */
    -moz-transform: scaleX(-1);
    transform: scaleX(-1);
    /* Firefox特定的视频修复 */
    background: #000;
    display: block;
    /* 确保视频元素在Firefox中正确显示 */
    position: relative;
    z-index: 1;
  }
  
  .video-container {
    /* 修复Firefox中的视频容器 */
    position: relative;
    overflow: hidden;
    background: #000;
    /* 确保容器在Firefox中正确显示 */
    display: block;
  }
}
</style>